import { useCallback, useState, useEffect, useRef } from 'react';
const initPageInfo = {
  offset: 0, // （page - 1） * limit 作为当前起始偏移量
  limit: 24, // 一页展示多少条数据
  page: 1, // 当前页数
};
interface ISendData {
  limit?: number;
  offset?: number;
  collectOnly?: boolean;
  keyword?: string;
}

export default function useScrollData<T>(request: (...args: any[]) => Promise<{ list: T[] }>) {
  const [panelList, setPanelList] = useState([] as T[]); // 数据
  const [collectOnly, setCollectOnly] = useState<boolean>(false); // 是否收藏
  const [loading, setLoading] = useState(false); // 等待
  const [flag, setFlag] = useState(false); // 标志
  const [isFinish, setIsFinish] = useState(false); // 结束
  const [keyword, setKeyword] = useState<string>(''); //关键字

  // 无限下拉列表，pageInfo不会作为渲染依据
  const pageInfo = useRef({ ...initPageInfo });

  // 筛选变化
  useEffect(() => {
    pageInfo.current = { ...initPageInfo };
    setIsFinish(false);
    setPanelList([]);

    const { offset, limit } = pageInfo.current;

    setLoading(true);
    const sendData: ISendData = { collectOnly, offset, limit };
    if (keyword.trim().toString().length !== 0) sendData.keyword = keyword;
    request(sendData)
      .then(({ list }) => {
        setPanelList(list);
        if (list.length === 0) {
          // 表示下面没有数据了 可以结束了
          setIsFinish(true);
        }
      })
      .finally(() => setLoading(false));
  }, [collectOnly, flag, keyword, request]);

  const nextPage = useCallback(() => {
    pageInfo.current.page += 1;
    pageInfo.current.offset = (pageInfo.current.page - 1) * pageInfo.current.limit;
    const { offset, limit } = pageInfo.current;

    setLoading(true);
    const sendData: ISendData = { collectOnly, offset, limit };
    if (keyword.trim().toString().length !== 0) sendData.keyword = keyword;
    request(sendData)
      .then(({ list }) => {
        setPanelList((v) => [...v, ...list]);
        if (list.length === 0) {
          setIsFinish(true);
        }
      })
      .finally(() => setLoading(false));
  }, [collectOnly, keyword, request]);

  const refresh = () => setFlag((v) => !v);

  return {
    panelList,
    loading,
    nextPage,
    refresh,
    isFinish,
    collectOnly,
    setCollectOnly,
    setKeyword,
  };
}
